package com.fadadianqi.mall.product.service;

import com.fadadianqi.commons.PrimaryKeyCreator;
import com.fadadianqi.mall.product.dao.AttrNameDAO;
import com.fadadianqi.mall.product.dao.AttrRelationDAO;
import com.fadadianqi.mall.product.dao.AttrValDAO;
import com.fadadianqi.mall.product.dao.ItemSPUAttrDAO;
import com.fadadianqi.mall.product.model.AttrName;
import com.fadadianqi.mall.product.model.AttrRelation;
import com.fadadianqi.mall.product.model.AttrVal;
import com.fadadianqi.mall.product.model.ItemSPUAttr;
import com.sun.org.apache.commons.logging.Log;
import com.sun.org.apache.commons.logging.LogFactory;
import com.yeqiangwei.commons.util.BeanUtils;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by aroot on 2/12/14.
 */
@Service
public class AttrService {

    private static final Log log = LogFactory.getLog(AttrService.class);
    @Autowired
    private AttrValDAO attrValDAO;
    @Autowired
    private AttrNameDAO attrNameDAO;
    @Autowired
    private AttrRelationDAO attrRelationDAO;

    @Autowired
    private ItemSPUAttrDAO itemSPUAttrDAO;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void update(AttrForm form) {
        String navAttrId = form.getNavAttrId();
        AttrRelation attrRelation = attrRelationDAO.getById(navAttrId);
        if(null == attrRelation) {
            log.warn("exception.mall.product.attribute.attrRelation.notFound");
        }
        attrRelation.setOrderby(form.getOrderby());
        attrRelation.setIsImage(form.getIsImage());
        attrRelation.setIsMultiple(form.getIsMultiple());
        attrRelation.setIsRequired(form.getIsRequired());
        attrRelation.setIsSale(form.getIsSale());
        attrRelationDAO.update(attrRelation);
        AttrName attrName = attrNameDAO.getById(attrRelation.getAttrNameId());
        attrName.setName(form.getName());
        attrNameDAO.update(attrName);
        HashSet<String> allValSet = new HashSet<String>();
        if (ValidatorHelper.isNotEmpty(form.getVals())) {
            Iterator<AttrVal> vals = form.getVals().iterator();
            while (vals.hasNext()) {
                AttrVal attrVal = vals.next();
                if(ValidatorHelper.isEmpty(attrVal.getVal())
                        && ValidatorHelper.isEmpty(attrVal.getAlias())) {
                    log.warn("AttrVal alias and val is empty!!!");
                    continue;
                }
                if(ValidatorHelper.isEmpty(attrVal.getVal())) {
                    attrVal.setVal(attrVal.getAlias());
                }
                allValSet.add(attrVal.getVal());
                AttrVal val = attrValDAO.getByVal(attrVal.getVal());
                if (null == val) {
                    val = new AttrVal();
                    val.setId(PrimaryKeyCreator.create());
                    val.setAttrNameId(attrName.getId());
                    val.setVal(attrVal.getVal());
                    val.setAlias(attrVal.getAlias());
                    if(ValidatorHelper.isNotEmpty(val.getVal())
                            && ValidatorHelper.isNotEmpty(val.getAlias())) {
                        attrValDAO.create(val);
                    }
                }
                else {
                    val.setVal(attrVal.getVal());
                    val.setAlias(attrVal.getAlias());
                    attrValDAO.update(val);
                }
            }
        }
        // 计算被删除的属性值
         List<AttrVal> allVals = attrValDAO.findByAttrNameId(attrName.getId());
        if(ValidatorHelper.isNotEmpty(allVals)) {
            for(AttrVal val : allVals) {
                if(!allValSet.contains(val.getVal())) {
                    // TODO 删除属性值可能需要关联删除一些信息，比如已经被商品选中的属性值。。。。
                    attrValDAO.remove(val);
                }
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void create(AttrForm form) throws AttrException {
        String relationId = form.getRelationId();
        if (ValidatorHelper.isEmpty(relationId)) {
            log.warn("exception.mall.product.attribute.navId.required");
            throw new AttrException("exception.mall.product.attribute.navId.required");
        }
        AttrName attrName = new AttrName();
        attrName.setId(PrimaryKeyCreator.create());
        attrName.setName(form.getName());
        attrNameDAO.create(attrName);
        if (ValidatorHelper.isNotEmpty(form.getVals())) {
            Iterator<AttrVal> vals = form.getVals().iterator();
            while (vals.hasNext()) {
                AttrVal attrVal = vals.next();
                if(ValidatorHelper.isEmpty(attrVal.getVal())
                        && ValidatorHelper.isEmpty(attrVal.getAlias())) {
                    log.warn("AttrVal alias and val is empty!!!");
                    continue;
                }
                if(ValidatorHelper.isEmpty(attrVal.getVal())) {
                    attrVal.setVal(attrVal.getAlias());
                }
                AttrVal val = attrValDAO.getByVal(attrVal.getVal());
                if (null == val) {
                    val = new AttrVal();
                    val.setId(PrimaryKeyCreator.create());
                    val.setAttrNameId(attrName.getId());
                    val.setVal(attrVal.getVal());
                    val.setAlias(attrVal.getAlias());
                    if(ValidatorHelper.isNotEmpty(val.getVal())
                            && ValidatorHelper.isNotEmpty(val.getAlias())) {
                        attrValDAO.create(val);
                    }
                }
            }
        }
        AttrRelation ar = attrRelationDAO.getByNavIdAndAttrNameId(relationId, attrName.getId());
        if (ar == null) {
            ar = new AttrRelation();
            BeanUtils.copyProperties(ar, form);
            ar.setId(PrimaryKeyCreator.create());
            ar.setAttrNameId(attrName.getId());
            attrRelationDAO.create(ar);
            form.setRelationId(ar.getId());
        } else {
            throw new AttrException("exception.mall.product.attribute.duplicate");
        }
    }

    public AttrRelation getAttrRelationById(String id) {
        return attrRelationDAO.getById(id);
    }

    public AttrName getAttrNameById(String attrNameId) {
        return attrNameDAO.getById(attrNameId);
    }

    public List<AttrRelation> findNavAttrByNavId(String navId) {
        return attrRelationDAO.findByNavId(navId);

    }

    public List<AttrVal> findAttrValByAttrNameId(String attrNameId) {
        return attrValDAO.findByAttrNameId(attrNameId);
    }

    public List<AttrVal> findAttrValByAttrName(AttrName attrName) {
        return findAttrValByAttrNameId(attrName.getId());
    }

    public AttrVal getAttrValById(String id) {
        return attrValDAO.getById(id);
    }

    public List<AttrVal> findAttrValBySpuId(String spuId) {
        if(ValidatorHelper.isEmpty(spuId)) {
            return null;
        }
        List<AttrVal> list = new ArrayList<AttrVal>();
        List<ItemSPUAttr> attrList = itemSPUAttrDAO.findBySpuId(spuId);
        if(ValidatorHelper.isNotEmpty(attrList)) {
            for(ItemSPUAttr itemSPUAttr : attrList) {
                AttrVal attrVal = attrValDAO.getById(itemSPUAttr.getAttrValId());
                list.add(attrVal);
            }
        }
        return list;
    }


    public static class AttrForm {

        private String navAttrId;
        private String name;
        private Set<AttrVal> vals;
        private String spuId;
        private String relationId;
        private int type = AttrRelation.TYPE_NAV;
        private int orderby = 0;
        private Boolean isMultiple = Boolean.FALSE; // 是否为多选
        private Boolean isSale = Boolean.FALSE; // 是否是销售属性，这将影响商品SKU。
        private Boolean isRequired = Boolean.FALSE; // 是否为必选
        private Boolean isImage = Boolean.FALSE; // 是否有图片

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public String getNavAttrId() {
            return navAttrId;
        }

        public void setNavAttrId(String navAttrId) {
            this.navAttrId = navAttrId;
        }

        public int getOrderby() {
            return orderby;
        }

        public void setOrderby(int orderby) {
            this.orderby = orderby;
        }

        public Boolean getIsMultiple() {
            return isMultiple;
        }

        public void setIsMultiple(Boolean isMultiple) {
            this.isMultiple = isMultiple;
        }

        public Boolean getIsSale() {
            return isSale;
        }

        public void setIsSale(Boolean isSale) {
            this.isSale = isSale;
        }

        public Boolean getIsRequired() {
            return isRequired;
        }

        public void setIsRequired(Boolean isRequired) {
            this.isRequired = isRequired;
        }

        public Boolean getIsImage() {
            return isImage;
        }

        public void setIsImage(Boolean isImage) {
            this.isImage = isImage;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Set<AttrVal> getVals() {
            return vals;
        }

        public void setVals(Set<AttrVal> vals) {
            this.vals = vals;
        }

        public String getSpuId() {
            return spuId;
        }

        public void setSpuId(String spuId) {
            this.spuId = spuId;
        }

        public String getRelationId() {
            return relationId;
        }

        public void setRelationId(String relationId) {
            this.relationId = relationId;
        }
    }

}
